<template>
    <div class="chat-main">
        <div
            class="chat-list-body"
            :class="{'is_menu_mini':is_menu_mini}"
            :style="{width: isMobileWidth() ? aiLayoutConfig.layout.left.mobileWidth : dragAreaWidth,}"
        >
            <div class="layout-toggle">
                <div class="layout-toggle-button" @click="is_menu_toggle">
                    <Icon v-if="is_menu" name="el-icon-ArrowRight" size="14"/>
                    <Icon v-else name="el-icon-ArrowLeft" size="14"/>
                </div>
            </div>
            <div class="drag" @mousedown="startDrag($event)"></div>
            <div>
                <div class="chat-list-box">
                    <div class="chat-list-header">
                        <div class="chat-list-header-top">
                            <div class="title">{{ siteConfig.siteName }}</div>
                            <a-tooltip>
                                <template #title>创建新的聊天</template>
                                <div class="button" @click="create_chat">
                                    <Icon name="iconfont icon-suifangguanli" size="20" />
                                </div>
                            </a-tooltip>
                        </div>
                        <div class="chat-list-header-input">
                            <a-input
                                v-model="search"
                                class="search"
                                placeholder="搜索对话内容..."
                                allow-clear
                                @change="getGroupList(search)"
                            >
                                <template #prefix>
                                    <div class="search-ico">
                                        <Icon name="iconfont icon-search" size="14" />
                                    </div>
                                </template>
                            </a-input>
                            <a-tag class="tag" :bordered="false" size="small">Ctrl K</a-tag>
                        </div>
                    </div>
                    <div class="chat-list-message">
                        <div v-if="state.loading">
                            <div class="list-item" v-for="item in 6" :key="item">
                                <a-skeleton avatar active :paragraph="{ rows: 1 }" />
                            </div>
                        </div>
                        <div v-else-if="groupList.length > 0">
                            <div
                                v-show="group_id"
                                v-for="item in groupList"
                                :key="item.id"
                                class="list-item"
                                :class="{'active':item.id === group_id}"
                                @click="message_item(item)"
                            >
                                <div class="item-box">
                                    <a-avatar class="avatar" :src="fullUrl(item.cover)" :size="42" :alt="item.name" />
                                    <div class="centre">
                                        <div class="title">{{ item.name }}</div>
                                        <div class="content">{{ item.title }}</div>
                                    </div>
                                    <div class="right">
                                        <div class="d1">{{ item.update_time }}</div>
                                        <div class="d2" @click="$event.stopPropagation()">
                                            <a-dropdown>
                                                <template #overlay>
                                                    <a-menu @click="handleMenuClick(item, $event)">
                                                        <a-menu-item key="top">顶置</a-menu-item>
                                                        <a-menu-item key="edit">编辑</a-menu-item>
                                                        <a-menu-divider />
                                                        <a-sub-menu key="sub1" title="移动到分组">
                                                            <a-menu-item disabled>分组1</a-menu-item>
                                                            <a-menu-item disabled>分组2</a-menu-item>
                                                            <a-menu-divider />
                                                            <a-menu-item disabled>添加新分组</a-menu-item>
                                                        </a-sub-menu>
                                                        <a-menu-item key="delete">
                                                            <div class="menu-item">
                                                                <!-- <Icon name="iconfont icon-search" size="14" />-->
                                                                <div>删除</div>
                                                            </div>
                                                        </a-menu-item>
                                                    </a-menu>
                                                </template>
                                                <Icon name="iconfont icon-gengduo" size="20" />
                                            </a-dropdown>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 没有数据 -->
                        <div v-else>
                            <div class="list-item active">
                                <div class="item-box">
                                    <a-avatar class="avatar" src="//thinkct.oss-cn-beijing.aliyuncs.com/static/images/ai.png" :size="42" />
                                    <div class="centre">
                                        <div class="title">AI助手</div>
<!--                                        <div class="content">1</div>-->
                                    </div>
                                    <div class="right">
                                    </div>
                                </div>
                            </div>
                            <div class="ddd122">
                                <a-collapse
                                    v-model:activeKey="activeKey"
                                    ghost
                                    expandIconPosition="end"
                                >
                                    <a-collapse-panel
                                        v-for="item in fenzu_list"
                                        :key="item.id"
                                        :header="item.name"
                                    >
                                        <div class="create_chat-button">
                                            <a-button @click="create_chat">新建助手</a-button>
                                        </div>
                                    </a-collapse-panel>
                                </a-collapse>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-if="is_menu_mini" class="overlay" @click="is_menu_mini_toggle"></div>
        <div class="chat-body">
            <div class="chat-header">
                <div class="top">
                    <div class="left-menu" @click="is_menu_mini_toggle">
                        <Icon name="iconfont icon-caidan2" size="20"/>
                    </div>
                    <div class="title">
                        <a-avatar
                            :size="40"
                            :src="fullUrl(state.group_info.cover || '/storage/default/20231104/aia5d1914f019d5a08c5ce6672d789c37dab8d52c3.png')"
                            :alt="state.group_info.name"
                            class="avatar"
                        />
                        <div class="info">
                            <div class="name">
                                <div class="nickname">{{ state.group_info.name || 'AI助手'}}</div>
                                <div class="tag-list">
                                    <a-tag color="green" size="small">机器人</a-tag>
                                    <a-tag size="small" @click="state.model_show = !state.model_show">
                                        <Icon name="iconfont icon-ChatGPT" size="13" />
                                        <!-- {{ state.group_info.model || 'gpt-3.5-turbo' }}-->
                                        {{ chatConfig.chat.model || 'gpt-3.5-turbo' }}
                                    </a-tag>
                                </div>
                            </div>
                            <div class="desc">
                                <span>{{ state.group_info.desc||'暂无描述' }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="center"></div>
                    <div class="right-menu">
                        <div class="nav-item" @click="state.model_show = !state.model_show">
                            <Icon name="iconfont icon-qita" size="20" />
                        </div>
                    </div>
                </div>
            </div>
            <chatModel :visible="state.model_show" :chantModel="state.chat_model" :groupId="Number(group_id)" />
            <ChatMessage :groupId="Number(group_id)" :groupInfo="state.group_info" :groupList="getGroupList"/>
            <div class="chat-footer" v-if="false">
                <el-text v-show="siteConfig.siteName" type="info" size="small">版权所有 © {{siteConfig.siteName}} {{siteConfig.recordNumber}}</el-text>
            </div>
        </div>
        <Notice />
    </div>
</template>

<script setup lang="ts">
import {reactive, watch, onMounted, ref, inject, provide} from 'vue'
import { useUserInfo } from '/@/stores/userInfo'
import { getGroup, createGroup, saveGroup, deleteGroup } from '/@/api/frontend/chat/ai/group'
import ChatMessage from '/@/layouts/frontend/components/chat/message.vue'
import { ElMessageBox } from 'element-plus'
import {useSiteConfig} from "/@/stores/siteConfig";
import {fullUrl, isMobileWidth} from "/@/utils/common";
import Icon from "/@/components/icon/index.vue";
import chatModel from "/@/layouts/frontend/components/chat/chatModel.vue";
import Notice from '/@/layouts/frontend/components/chat/notice.vue'
import { Modal, message } from 'ant-design-vue';
import {useAiLayoutConfig} from "/@/stores/aiLayoutConfig"
import { useChatConfig } from "/@/stores/openai/chatConfig"
// chatConfig
import { chatConfig as getChatConfig } from "/@/api/frontend/chat/webConfig"

// getChatConfig
getChatConfig()


const chatConfig = useChatConfig()
const activeKey = ref('1')
const fenzu_list = ref([
    {id: 1, name: '默认列表'},
    // {id: 2, name: '列表1'},
    // {id: 3, name: '列表2'},
])

const aiLayoutConfig = useAiLayoutConfig()
const handleMenuClick = (item: any, event: any) => {
    if(!userInfo.isLogin()) {
        state.login_show = !state.login_show
        return false;
    }
    if (event.key === 'top') {
        message.success('置顶成功');
    }
    if (event.key === 'edit') {
        ElMessageBox.prompt('昵称', '角色设置', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValue: item.name,
            inputPlaceholder: '请输入名称',
            inputPattern: /\S+/,
            inputErrorMessage: '请输入名称'
        }).then(({ value }) => {
            saveGroup({
                id: item.id,
                name: value,
            }).then((res) => {
                if (res.code == 1) {
                    item.name = value;
                }
            })
        });
    }

    if (event.key === 'delete') {
        Modal.confirm({
            title: '即将删除该助手',
            content: '删除后该将无法找回，请确认你的操作',
            okType: 'danger',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                deleteGroup(item.id).then((res) => {
                    if (res.code == 1) {
                        getGroupList();
                    }
                })
            }
        })
    }
}
// 拖拽
const dragAreaWidth = ref(aiLayoutConfig.layout.left.width) // 初始高度
const startDrag = (e: any) => {
    let targetDiv = document.getElementsByClassName("chat-list-body")[0];
    let targetDivWidth = targetDiv.clientWidth
    let startX = e.clientX;
    document.onmousemove =  (e) => {
        e.preventDefault();
        let distX = Math.abs(e.clientX - startX);
        dragAreaWidth.value = String(e.clientX < startX ? targetDivWidth - distX : targetDivWidth + distX) + 'px'
        aiLayoutConfig.setLeft({width: dragAreaWidth.value})
    }
    document.onmouseup = function () {
        document.onmousemove = null;
    }
}
// 拖拽结束

const siteConfig = useSiteConfig()
const userInfo = useUserInfo()

const state: {
    loading: boolean,
    login_show: boolean,
    model_show: boolean,
    chat_model: string,
    pageLoading: boolean,
    group_message_count: number,
    message: any,
    total: number,
    currentPage: number,
    pageSize: number,
    group_info: any,
} = reactive({
    loading: false,
    login_show: inject('login_show', ref(false)),
    model_show: false,
    chat_model: '',
    pageLoading: true,
    group_message_count: 0,
    message: {
        list: {id: 1, role: "", content: ""},
    },
    total: 0,
    currentPage: 1,
    pageSize: 10,
    group_info: {},
})

// 聊天消息
provide('chat_message', state.message)

// 菜单显示隐藏
const is_menu = ref(false)
const is_menu_mini = ref(false)
const is_menu_toggle = () => {
    if (is_menu.value) {
        dragAreaWidth.value = '320px'
        is_menu.value = false
    } else {
        dragAreaWidth.value = '0px'
        is_menu.value = true
    }
}
const is_menu_mini_toggle = () => {
    is_menu_mini.value = !is_menu_mini.value;
}

// 滚动条最底部
// const onBottom = ref(false)
// provide('onBottom', onBottom)
// const scrollToBottom = () => {
//     onBottom.value = true
// }

// ##获取消息列表
const search = ref('');
const group_id = ref(0);
const group_title = ref('');
const groupList = ref([
    {
        id: 1,
        title: '新的聊天',
        name: '新的聊天',
        cover: '/storage/default/20231104/aia5d1914f019d5a08c5ce6672d789c37dab8d52c3.png',
        message_count: 0,
        model: 'gpt-3.5-turbo',
        update_time: '',
    }
])

// 获取消息列表
const getGroupList = (search = '', page = 1, pageSize = 30) => {
    state.loading = true
    getGroup(search, page, pageSize).then((res) => {
        if (res.code == 1) {
            state.loading = false
            groupList.value = res.data.list;
            // 判断groupList.value[0].id是否存在
            group_id.value = groupList.value[0]?.id;
            if (groupList.value[0]?.id) {
                group_id.value = groupList.value[0].id;
                group_title.value = groupList.value[0].title;
                state.group_info = groupList.value[0];
                //console.log(state.group_info)
                state.group_message_count = groupList.value[0].message_count;
                state.chat_model = groupList.value[0].model;
            }
        }
    })
}

// 加载请求
onMounted(() => {
    getGroupList();
})

// 监听分组搜索
// watch(search, (value) => {
//     getGroupList(value);
// })

// 点击分组列表
const message_item = (item: any) => {
    is_menu_mini.value = false;
    group_id.value = item.id;
    group_title.value = item.title;
    state.group_message_count = item.message_count;
    state.chat_model = item.model;
    state.group_info = item;
}

// 创建新的分组
const create_chat = () => {
    // 判断是否登录
    if(!userInfo.isLogin()) {
        state.login_show = !state.login_show
        return false;
    }
    createGroup('新的聊天').then((res) => {
        if (res.code == 1) {
            getGroupList();
        }
    })
}
</script>

<style scoped lang="scss">
.ddd122 {
    .ant-collapse-header {
        padding: 0;
        .ant-collapse-arrow {
            right: 10px;
        }
        //.ant-collapse-header-text {
        //    color: #999!important;
        //}
    }
    .ant-collapse-content-box {
        padding: 0;
    }
    .ant-collapse-content {
        padding: 0;
    }
}

.create_chat-button {
    display: flex;
    justify-content: center;
    .ant-btn-default {
        width: 100%;
        height: 36px;
    }
}

.slider-demo-block {
    display: flex;
    align-items: center;
    padding: 0 15px 15px 10px;
}
.slider-demo-block .el-slider {
    margin-top: 0;
    margin-left: 12px;
}
.slider-demo-block .demonstration {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    line-height: 44px;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 0;
}
.slider-demo-block .demonstration + .el-slider {
    flex: 0 0 70%;
}
</style>
